package controllers

import (
	"time"
	"github.com/robvdl/pongo2gin"
	"github.com/gin-gonic/gin"
	"github.com/itsjamie/gin-cors"
	"titargo/socket"
	"github.com/srinathgs/mysqlstore"
	"titargo/models"
)

var r *gin.Engine

var Store *mysqlstore.MySQLStore

func init() {

	hub := socket.NewHub()
	go hub.Run()
	//session
	gin.SetMode(gin.ReleaseMode)
	//路由开始
	r = gin.Default()
	r.HTMLRender = pongo2gin.Default()
	r.Use(cors.Middleware(cors.Config{
		Origins:         "*",
		Methods:         "GET, PUT, POST, DELETE",
		RequestHeaders:  "Origin, Authorization, Content-Type",
		ExposedHeaders:  "",
		MaxAge:          50 * time.Second,
		Credentials:     true,
		ValidateHeaders: false,
	}))
	r.Static("/static", "./static")

	r.NoRoute(notFoundFunc)
	r.GET("/", homeFunc)
	r.GET("/captcha", captchaFunc)
	r.Any("/login",loginFunc)
	r.Any("/register",registerFunc)
	r.GET("/logout",logoutFunc)
	r.GET("/ws",func(c *gin.Context){
		socket.WsHandler(GetUser(c),hub,c)
	})

	var encrypt = r.Group("/encrypt")
	encrypt.Use(Auth())
	{
		encrypt.GET("md5",encryptMd5ViewFunc)
		encrypt.POST("md5",encryptMd5HandFunc)
	}

	var chat = r.Group("/chat")
	chat.Use(Auth())
	{
		chat.GET("room",chatRoomFunc)
	}
}

func GetRoute() *gin.Engine {
	Store, _ = mysqlstore.NewMySQLStoreFromConnection(models.GetEngine().DB().DB,
		"sessions", "/", 3600, []byte("secret-key"))

	return r
}
